package com.example.alarmdemo;


import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";
    private static Date curDate = new Date(System.currentTimeMillis());//获取当前时间
    private static SimpleDateFormat formatter = new  SimpleDateFormat("yyyyMMddHHmmss");
    private static String strTime = formatter.format(curDate);
    /**
     * 是否开启日志输出,在Debug状态下开启,
     * 在Release状态下关闭以提示程序性能
     */
    public static final boolean DEBUG = true;

    /**
     * 系统默认的UncaughtException处理类
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    /**
     * CrashHandler实例
     */
    private static CrashHandler INSTANCE;

    /**
     * 程序的Context对象
     */
    private Context mContext;
    //用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();

    //单例模式

    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new CrashHandler();
        }
        return INSTANCE;
    }

    /**
     * 初始化,注册Context对象,
     * 获取系统默认的UncaughtException处理器,
     * 设置该CrashHandler为程序的默认处理器
     *
     * @param ctx
     */
    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        handleException(throwable);//自定义处理
        mDefaultHandler.uncaughtException(thread, throwable);//除了放到log文件内,让系统也可以默认处理
        try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
        }
        android.os.Process.killProcess(android.os.Process.myPid());//强退崩一次
        System.exit(1);

    }

    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        //系统本身有报错信息,可能会与下面的报错信息冲突,所以去掉下面提示;
        /*new Thread() {
            @Override
            public void run() {
                Looper.prepare();//准备发消息的MessageQueue
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();//同步消息,只要有looper就能用.
                Looper.loop();
            }
        }.start();*/
       MyApplication.crashFileName =  saveCrashInfo2File(mContext,ex);//保存设备参数以及错误日志到文件中

        return true;
    }
//设备信息
    private void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field :
                fields) {
            field.setAccessible(true);
            try {
                infos.put(field.getName(),field.get(null).toString());
                Log.e(TAG,field.getName()+" : "+field.get(null));
            } catch (IllegalAccessException e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }

        }
    }

    /**
     * 保存错误信息到文件中
     * @param ex
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Context ctx,Throwable ex){
        collectDeviceInfo(ctx);
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);//错误信息print中写
            cause = cause.getCause();
        }
        printWriter.close();
        String result  = writer.toString();
        sb.append(result);
        try {
            long timeStamp = System.currentTimeMillis();
            //String fileName = "crash-" +strTime+"-"+timeStamp+".log";
            String fileName = "LinphoneCrash.log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = Environment.getExternalStorageDirectory().getPath()+"/crash/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                    FileOutputStream fos = new FileOutputStream(path+fileName);
                    fos.write(sb.toString().getBytes());
                    fos.close();
                }
            return  fileName;
        }catch  (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
            return  null;
    }

}
